<?php

/**
 * AuthItemForm class.
 * AuthItemForm is the data structure for keeping
 */
class AuthItemForm extends CFormModel
{
    public $name;
    public $nameOld;
    public $description;
    public $bizrule;
    public $type;
    public $data;
    public $isNew=1;

    /**
     */
    public function rules()
    {
        return array(
            array('name', 'uniqueRole'),
            array('description, bizrule, type, data, isNew, nameOld', 'safe'),
        );
    }
    
    public function uniqueRole($attribute, $params)
    {
        $this->{$attribute} = trim($this->{$attribute});
        if ($this->isNew)
        {
            /** @var CDbAuthManager */
            $authManager = Yii::app()->authManager;
            $authItem = $authManager->getAuthItem($this->{$attribute});
            if ($authItem !== null)
            {
                $this->addError('name', 'Role is exists');
                return false;
            }
        }
        return true;
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels()
    {
        return array(
            'name'=>'Name',
            'description'=>'Description',
            'bizrule'=>'BizRule',
            'data'=>'Data',
        );
    }
    
    public function findRole($name)
    {
        /** @var CDbAuthManager */
        $authManager = Yii::app()->authManager;
        $authItem = $authManager->getAuthItem($name);
        if ($authItem !== null)
        {
            $this->nameOld = $this->name = $authItem->name;
            $this->description = $authItem->description;
            $this->bizrule = $authItem->bizrule;
            $this->data = $authItem->data;
            $this->type = $authItem->type;
            $this->isNew = 0;
        }
        return $this;
    }
    
    public function save()
    {
        /** @var CDbAuthManager */
        $authManager = Yii::app()->authManager;
        if ($this->isNew)
        {
            $authManager->createAuthItem($this->name, $this->type, $this->description, $this->bizrule, $this->data);
        }
        else
        {
            $authItem = $authManager->getAuthItem($this->nameOld);
            $authItem->description = $this->description;
            $authItem->bizrule = $this->bizrule;
            $authItem->data = $this->data;
            if ($this->nameOld !== $this->name)//change name
            {
                $authItem->name = $this->name;
                $authManager->saveAuthItem($authItem, $this->nameOld);
            }
            else
                $authManager->saveAuthItem($authItem);
        }
        return true;
    }
}
